package xyz.yuanjilu;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSON;
import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.plugin.MongoPlugin;
import com.mongodb.MongoClient;

import xyz.yuanjilu.utils.PropertiesHelper;
import xyz.yuanjilu.utils.StringUtils;

@Configuration
public class MongoBeanConfig {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private PropertiesHelper propertiesHelper;
	@Value("${mongo.dbname}")
	private String dataBase;
	@Value("${mongo.nodecount}")
	private int nodecount;
	
	@Value("${mongo.username}")
	private String username;
	@Value("${mongo.password}")
	private String password;
	
	@Bean("mongoPlugin")
	public MongoPlugin getMongoPlugin() {
		Map<String, String> pmap = propertiesHelper.getMap("mongo.");
		MongoPlugin mongoPlugin=new MongoPlugin();
		
		logger.info("初始化mongoPlugin");
		logger.info(JSON.toJSONString(pmap));
		for (int i = 1; i <= nodecount; i++) {
			String nodeHost = pmap.get("host."+i);
			logger.info("加载节点["+i+"]"+nodeHost);
			mongoPlugin.add(nodeHost, Integer.parseInt(pmap.get("port."+i)));
		}
		mongoPlugin.setDatabase(dataBase);
		MongoClient mongoClient =null;
		if (StringUtils.isNotBlank(username)) {
			mongoPlugin.auth(username, password);
		}
		mongoClient = mongoPlugin.getMongoClient();
		MongoKit.INSTANCE.init(mongoClient, mongoPlugin.getDatabase());
		logger.info("初始化mongo链接到数据"+dataBase);
		
		
		return mongoPlugin;
	}
	
}
